<template>
  <div>
    <div class="message_div" :style="{ 'margin-top': showChart ? '100%' : '0' }">

      <div
        v-for="(chat, index) in chatList"
        :key="index"
        class="chat-item"
        @touchstart="handleTouchStart(index)"
        @touchmove="handleTouchMove(index, $event)"
        @click="messageUrl(chat)"
      >
        <div class="online-indicator" v-if="chat.status"></div>
        <!-- 显示头像 -->
        <img class="avatar" :src="chat.avatar" alt="Avatar">
        <div class="chat-content">
          <!-- 显示昵称 -->
          <div class="nickName">
            <p><strong>{{ chat.name }}</strong></p>
          </div>
          <div class="lastMessage">
            <p>{{ chat.lastMessage.content }}</p> <!-- 显示最后一条消息 -->
          </div>

          <div class="lastMessageTime">
            <p>{{ chat.lastMessage.timestamp }}</p> <!-- 显示最后一条消息的发送时间 -->
          </div>
          <div class="notification-icon" v-if="chat.missReadCount>0">
            <span class="notification-count">{{chat.missReadCount}}</span>
          </div>
        </div>
        <div class="delete-btn" :style="{ 'margin-right': index === leftBar ? '0px' : '-110px'}" @click="deleteChat(index)">
          删除
        </div>
      </div>
    </div>

  </div>
</template>
<script>
import config from "../../config"


export default {

  data() {
    return {
      openid:'',
      ec: {},
      showChart: false,
      leftBar: '',
      chatList: [
        { nickname: '张三', avatar: 'https://c-ssl.duitang.com/uploads/blog/202206/12/20220612164733_72d8b.jpg', message: '最近消息', online: true },
        { nickname: '李四', avatar: 'https://c-ssl.duitang.com/uploads/blog/202309/15/AvSLwpOjCwVM28A.png', message: '最近消息', online: false },
        { nickname: '王五', avatar: 'https://c-ssl.duitang.com/uploads/blog/202401/22/m7SDnxoZHN6e1jO.jpeg', message: '最近消息', online: true },
      ],
      startX: 0,
      startY: 0,
      searchKeyword: '', // 新增医生搜索关键词
    };
  },
  onShow() {
    this.init();
    this.initWebSocket();
  },
  onReady() {
  },
  onHide() {
    wx.closeSocket({
      success(res) {
        console.log("主动断开连接");
      }
    });
  },
  methods: {
    timeTran(dateNow){
      let date;
      if(dateNow===null)
        date = new Date();
      else
        date = new Date(dateNow);
      const month = date.getMonth() + 1;
      const day = date.getDate();
      const hour = date.getHours();
      const minu = date.getMinutes();
      const now1 = month < 10 ? '0' + month : month;
      const now2 = day < 10 ? '0' + day : day;
      return now1 + '-' + now2 + ' ' + hour + ':' + minu
    },
    initWebSocket(){
      const openid=this.openid
      /*开启websocket服务*/
      wx.connectSocket({
        url: 'ws://127.0.0.1:8081/imserver/' + openid,
        success: () => {
          console.log('WebSocket连接打开成功');
          this.socketOpen = true;

          // 设置 WebSocket 事件监听
          wx.onSocketMessage((res) => {
            console.log('收到服务器消息:', res.data);
            const data=JSON.parse(res.data.toString())
            this.updateMessage(data)
          });

          wx.onSocketError((error) => {
            console.error('WebSocket错误:', error);
          });

          wx.onSocketClose((res) => {
            console.log('WebSocket连接已关闭:', res);
            this.socketOpen = false;
          });
        },
        fail: (error) => {
          console.error('WebSocket连接打开失败', error);
        },
      });
    },
    clearPlaceholder(){
      //搜索医生字样消失
      this.placeholderText=''
    },
    restorePlaceholder(){
      //搜索医生字样恢复
      this.placeholderText='搜索医生'
    },
    init() {
      const doctorUrl = config.doctorByUrl;

      if (wx.getStorageSync("doctorInfo") !== '') {
        this.openid = JSON.parse(wx.getStorageSync("doctorInfo")).doctorId;
      } else {
        wx.showToast({
          title: '尚未登入',
          icon: 'none',
          duration: 1500,
        });
      }
      wx.request({
        method: "POST",
        url: doctorUrl,
        data: {
          doctorId: this.openid
        },
        success: (res) => {
          this.chatList = res.data.data;
          for(let i=0; i<this.chatList.length; i++){
            this.chatList[i].lastMessage.timestamp = this.timeTran(this.chatList[i].lastMessage.timestamp)
          }
        }
      });
    },
    updateMessage(data){
      console.log(data.text)
      this.chatList.forEach(chat=>{
        if(chat.doctorId === data.from)
        {
          chat.missReadCount++;
          chat.lastMessage.content=data.text;
          chat.lastMessage.timestamp=this.timeTran(null);
          return
        }
      })
      this.init();
    },
    toggleChart() {
      this.showChart = !this.showChart;
    },
    handleTouchStart(index) {
      this.startX = 0;
      this.startY = 0;
      this.leftBar = null;
    },
    handleTouchMove(index, event) {
      const touch = event.touches[0];
      if (!this.startX || !this.startY) {
        this.startX = touch.clientX;
        this.startY = touch.clientY;
        return;
      }
      const deltaX = touch.clientX - this.startX;
      if (deltaX < 0) {
        // horizontal swipe
        this.leftBar = index;
      }
      if (deltaX > 0) {
        this.leftBar = null;
      }
    },
    deleteChat(index) {
      this.chatList.splice(index, 1);
    },
    messageUrl(index) {
      wx.navigateTo({
        url: "/pages/messageDetail/main?user="+JSON.stringify(index)+"&doctor=''"
      });
    },
    // 新增搜索医生方法
    searchDoctor() {
      // 实现医生搜索逻辑，例如根据搜索关键词过滤 chatList

      wx.showLoading({
        title: '加载中',
        mask:true
      })
      const key=this.searchKeyword
      setTimeout(function () {
        wx.hideLoading()
        wx.navigateTo({
          url:'/pages/doctorSearch/main?key='+key
        })
      }, 1000)




    }
  },
};
</script>

<style scoped>
.notification-icon {
  left: 86%;
  width: 20px;
  height: 20px;
  position: absolute;
  background-color: #f00;
  border-radius: 50%;
  color: white;
  text-align: center;
  line-height: 20px;
}

.notification-count {
  font-weight: bolder;
  position: absolute;
  top: 0;
  right: 0;
  width: 20px;
  height: 20px;
}
.message_div {
  position: absolute;
  left: 0;
  height: 70%;
  width: 100%;
  background-color: white;
  transition: margin-top 0.5s;
}

.chat-item {
  display: flex;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #ccc;
}

.chat-content {
  text-align: center;
  line-height: 0px;
  flex: 1;
}

.delete-btn {
  width: 80px;
  background-color: #ff3b30;
  color: white;
  text-align: center;
  line-height: 40px;
  font-size: 14px;
  cursor: pointer;
  transition: margin-right 0.3s;
}

.online-indicator {
  width: 10px;
  height: 10px;
  background-color: #4caf50;
  border-radius: 50%;
  margin-right: 10px;
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-left: 10px;
  position: absolute;
  left: 6%;
}

.nickName {
  position: absolute;
  left: 29%;
  text-align: center;
  margin-top: -3.5%;
}

.lastMessage {
  position: absolute;
  left: 29%;
  text-align: left;
  margin-top: 1.5%;
  color: #847c7c;
  font-size: 13px;
  width: 150px;
  height: 13px;
  line-height: 13px;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;
  overflow:hidden;
}

.lastMessageTime {
  position: absolute;
  left: 76%;
  text-align: center;
  margin-top: -3.5%;
  color: #847c7c;
  font-size: 13px;
}


</style>
